import { AfterViewInit, Component, Injector, ViewEncapsulation, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentFactory, ComponentRef, OnDestroy, OnInit } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { FlowworkauditDetailModelComponent } from '../flowworkauditDetailModel/flowworkauditDetailModel.component';
import { EntityDtoOfInt64, UserListDto, WorkflowServiceProxy, UserServiceProxy, GetWorkflowInstanceViewDto, OrganizationUnitServiceProxy, WorkflowStatus, WorkflowInstanceDto } from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import * as _ from 'lodash';

@Component({
    selector: 'outsourcingApplicationList',
    templateUrl: './OutsourcingApplicationList.component.html',
    styleUrls: ['./OutsourcingApplicationList.component.css']
})
export class OutsourcingApplicationListComponent extends AppComponentBase {
    @ViewChild('flowworkauditDetailModel') flowworkauditDetailModel: FlowworkauditDetailModelComponent;
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    getWorkflowInstanceViewDtos: GetWorkflowInstanceViewDto[];

    filterText = '';
    constructor(injector: Injector,
        private _workflowServiceProxy: WorkflowServiceProxy,
        private _userServiceProxy: UserServiceProxy) {
        super(injector);
    }

    getOutSourcingAppLicationWorkflow(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }

        this.primengTableHelper.showLoadingIndicator();

        this._workflowServiceProxy.getALLInstance(
            this.primengTableHelper.getMaxResultCount(this.paginator, event),
            this.primengTableHelper.getSkipCount(this.paginator, event),
            this.filterText
        )
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
            .subscribe(result => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.getWorkflowInstanceViewDtos = result.items;
                this.primengTableHelper.hideLoadingIndicator();
                _.forEach(this.getWorkflowInstanceViewDtos, viewItem => {
                    this._workflowServiceProxy.getOpenUserActions(viewItem.id)
                        .subscribe(actionResult => {
                            let currentD = this.getWorkflowInstanceViewDtos.find((element) => (element.id === viewItem.id));
                            currentD.currentStepName = actionResult[0].prompt;
                            if (actionResult[0].assignedPrincipal) {
                                this._userServiceProxy.getUserForAll(actionResult[0].assignedPrincipal)
                                    .subscribe(userResult => {
                                        if (userResult.allOrganizationUnits.length > 0) {
                                            currentD.currentStepUserOuName = userResult.allOrganizationUnits[0].displayName;
                                        }
                                        currentD.currentStepUserName = userResult.user.name;
                                    });
                            }else
                            {
                                currentD.currentStepUserOuName="-";
                                currentD.currentStepUserName="-";
                            }
                        });
                });
            });
    }

    dateDifference(actualDate): string {
        // Calculate time between two dates:
        const date1 = actualDate; // the date you already commented/ posted
        const date2: any = new Date(); // today

        let r = {}; // object for clarity
        let message: string;

        const diffInSeconds = Math.abs(date2 - date1) / 1000;
        const days = Math.floor(diffInSeconds / 60 / 60 / 24);
        const hours = Math.floor(diffInSeconds / 60 / 60 % 24);
        const minutes = Math.floor(diffInSeconds / 60 % 60);
        const seconds = Math.floor(diffInSeconds % 60);
        const milliseconds = Math.round((diffInSeconds - Math.floor(diffInSeconds)) * 1000);

        const months = Math.floor(days / 31);
        const years = Math.floor(months / 12);

        // the below object is just optional
        // if you want to return an object instead of a message
        r = {
            years: years,
            months: months,
            days: days,
            hours: hours,
            minutes: minutes,
            seconds: seconds,
            milliseconds: milliseconds
        };

        // check if difference is in years or months
        if (years === 0 && months === 0) {
            // show in days if no years / months
            if (days > 0) {
                if (days === 1) {
                    message = days + ' 天';
                } else { message = days + ' 天'; }
            } else if (hours > 0) {
                if (hours === 1) {
                    message = hours + ' 小时';
                } else {
                    message = hours + ' 小时';
                }
            } else {
                // show in minutes if no years / months / days
                if (minutes === 1) {
                    message = minutes + ' 分钟';
                } else {
                    message = minutes + ' 分钟';
                }
            }
        } else if (years === 0 && months > 0) {
            // show in months if no years
            if (months === 1) {
                message = months + ' 月';
            } else {
                message = months + ' 月';
            }
        } else if (years > 0) {
            // show in years if years exist
            if (years === 1) {
                message = years + ' 年';
            } else {
                message = years + ' 年';
            }
        }

        return message + ' 前';
        // this is the message a user see in the view
    }

    Detail(records) {
        this.flowworkauditDetailModel.show(records.workflowDefinitionId, records.id);
    }

}
